<?php
/**
 * 文章管理
 */
defined('BASEPATH') OR exit('No direct script access allowed');

class News extends CI_Controller
{
    private $token_user,$admin_id;
    public function __construct()
    {
        parent::__construct();
        $this->token_user = check_token();
        $this->admin_id = $this->token_user[0];
        $this->load->model(array('admin_model','admin_group_model', 'report_model'));
    }

    public function index($opt = '')
    {
        //权限检查
        if(!$this->admin_group_model->check_perm('news_pages',$this->token_user[3]))
        {
            response_json([],101,'权限错误，请联系管理员');
        }
        $opt = $this->input->get_post('opt');
        // 推荐，置顶，精华状态修改
        if($opt == 'is_show' || $opt == 'flag')
        {
            $id   = (integer)$this->input->get_post('id');
            $update     = array(
                $opt => intval($this->input->get_post('val')),
            );
            $this->news_model->update($id, $update);
            response_json();
        }
        if($opt == 'add')
        {
            if($_SERVER['REQUEST_METHOD']=='POST')
            {
                $tag = $this->input->get_post('tag');
                $news_type_id = (int)$this->input->get_post('news_type_id');
                $title = $this->input->get_post('title');
                $short_title = $this->input->get_post('short_title');
                $keywords = $this->input->get_post('keywords');
                $lit_pic = $this->input->get_post('lit_pic');
                $description = $this->input->get_post('description');
                $jump_url = $this->input->get_post('jump_url');
                $author = $this->input->get_post('author');
                $source_from = $this->input->get_post('source_from');
                $sortrank = $this->input->get_post('sortrank');
                $title_color = $this->input->get_post('title_color');
                $seo_uri = $this->input->get_post('seo_uri');
                $pub_time = $this->input->get_post('pub_time');
                $mall_id = $this->input->get_post('mall_ids'); // 店铺id，逗号分割
                $body = $this->input->get_post('body'); // 店铺id，逗号分割

                if(empty($title))
                {
                    response_json([],'101',"请填写标题!");
                }
                if(empty($news_type_id))
                {
                    response_json([],'101',"请选择分类!");
                }

                // 标签处理
                $tags = "";
                if(strlen($tag) > 0){
                    $tag = str_replace("，",',',$tag);
                    $tags = array_filter(explode(",",$tag));
                }
                // 店铺处理
                $mall_ids = "";
                if(strlen($mall_id) > 0){
                    $mall_id = str_replace("，",',',$mall_id);
                    $mall_ids = array_filter(explode(",",$mall_id));
                }

                // 事务开始
                $this->db->trans_strict(FALSE); // 关闭严格模式，以免死锁
                $this->db->trans_begin();
                $insert = array(
                    'news_type_id' => $news_type_id,
                    'title' => $title,
                    'short_title' => $short_title,
                    'lit_pic' => $lit_pic,
                    'keywords' => $keywords,
                    'description' => $description,
                    'jump_url' => $jump_url,
                    'author' => $author,
                    'source_from' => $source_from,
                    'admin_id' => $this->admin_id,
                    'sortrank' => $sortrank,
                    'title_color' => $title_color,
                    'seo_uri' => $seo_uri,
                    'pub_time' => $pub_time,
                    'created_at' => date('Y-m-d H:i:s'),
                );
                $id = $this->news_model->insert($insert);
                // 处理新闻内容
                $body_insert = array(
                    'news_type_id' => $news_type_id,
                    'news_id' => $id,
                    'body' => $body
                );
                $this->news_bodies_model->insert($body_insert);

                if(!empty($tags)){
                    // 移除该标题下所有标签关系，以备新的插入
                    $this->news_data_tag_model->delete_where('news_id',$id);
                    foreach($tags as $t){
                        // 查询是否已经存在
                        $db_tag = $this->tag_model->get_by_field('name',$t);
                        if(empty($db_tag)){
                            // 插入字典表
                            $insert = array(
                                'name' => $t,
                                'create_at' => date('Y-m-d H:i:s'),
                            );
                            $tag_id = $this->tag_model->insert($insert);
                        }else{
                            $tag_id = $db_tag['id'];
                        }
                        // 插入关系表
                        $insert = array(
                            'news_id' => $id,
                            'tag_id' => $tag_id,
                            'tag_name' => $t,
                            'create_at' => date('Y-m-d H:i:s'),
                        );
                        $this->news_data_tag_model->insert($insert);
                    }

                }
                // 处理新闻关系表
                if(!empty($mall_ids)){
                    foreach($mall_ids as $mid){
                        $insert = array(
                            'news_id' => $id,
                            'mall_id' => $mid,
                            'created_at' => date('Y-m-d H:i:s'),
                        );
                        $this->news_mall_model->insert($insert);
                    }
                }

                if ($this->db->trans_status() === FALSE)
                {
                    $this->db->trans_rollback();
                    response_json([],'101',"添加失败，请重试!");
                }
                else
                {
                    $this->db->trans_commit();
                    response_json();
                }
            }
        }

        if($opt == 'edit')
        {
            $id   = (integer)$this->input->get_post('id');
            $info = $this->news_model->get_by_id($id);
            if(empty($info))
            {
                response_json([],'101',"参数错误!");
            }

            if($_SERVER['REQUEST_METHOD']=='POST')
            {
                $tag = $this->input->get_post('tag');
                $news_type_id = (int)$this->input->get_post('news_type_id');
                $title = $this->input->get_post('title');
                $short_title = $this->input->get_post('short_title');
                $keywords = $this->input->get_post('keywords');
                $lit_pic = $this->input->get_post('lit_pic');
                $description = $this->input->get_post('description');
                $jump_url = $this->input->get_post('jump_url');
                $author = $this->input->get_post('author');
                $source_from = $this->input->get_post('source_from');
                $sortrank = $this->input->get_post('sortrank');
                $title_color = $this->input->get_post('title_color');
                $seo_uri = $this->input->get_post('seo_uri');
                $pub_time = $this->input->get_post('pub_time');
                $mall_id = $this->input->get_post('mall_ids'); // 店铺id，逗号分割
                $body = $this->input->get_post('body'); // 店铺id，逗号分割

                if(empty($title))
                {
                    response_json([],'101',"请填写标题!");
                }
                if(empty($news_type_id))
                {
                    response_json([],'101',"请选择分类!");
                }

                // 标签处理
                $tags = "";
                if(strlen($tag) > 0){
                    $tag = str_replace("，",',',$tag);
                    $tags = array_filter(explode(",",$tag));
                }
                // 店铺处理
                $mall_ids = "";
                if(strlen($mall_id) > 0){
                    $mall_id = str_replace("，",',',$mall_id);
                    $mall_ids = array_filter(explode(",",$mall_id));
                }
                // 事务开始
                $this->db->trans_strict(FALSE); // 关闭严格模式，以免死锁
                $this->db->trans_begin();

                if(!empty($tags)){
                    // 移除该标题下所有标签关系，以备新的插入
                    $this->news_data_tag_model->delete_where('news_id',$id);
                    foreach($tags as $t){
                        // 查询是否已经存在
                        $db_tag = $this->tag_model->get_by_field('name',$t);
                        if(empty($db_tag)){
                            // 插入字典表
                            $insert = array(
                                'name' => $t,
                                'create_at' => date('Y-m-d H:i:s'),
                            );
                            $tag_id = $this->tag_model->insert($insert);
                        }else{
                            $tag_id = $db_tag['id'];
                        }
                        // 插入关系表
                        $insert = array(
                            'news_id' => $id,
                            'tag_id' => $tag_id,
                            'tag_name' => $t,
                            'create_at' => date('Y-m-d H:i:s'),
                        );
                        $this->news_data_tag_model->insert($insert);
                    }

                }

                $update = array(
                    'news_type_id' => $news_type_id,
                    'title' => $title,
                    'short_title' => $short_title,
                    'lit_pic' => $lit_pic,
                    'keywords' => $keywords,
                    'description' => $description,
                    'jump_url' => $jump_url,
                    'author' => $author,
                    'source_from' => $source_from,
                    'admin_id' => $this->admin_id,
                    'sortrank' => $sortrank,
                    'title_color' => $title_color,
                    'seo_uri' => $seo_uri,
                    'pub_time' => $pub_time,
                );
                $this->news_model->update($id, $update);
                // 处理新闻内容
                $body_update = array(
                    'news_type_id' => $news_type_id,
                    'body' => $body
                );
                $where = array(
                  'news_id' => $id
                );
                $this->db->update('news_bodies', $body_update, $where);
                // 处理新闻关系表
                if(!empty($mall_ids)){
                    $this->news_mall_model->delete_where('news_id',$id);
                    foreach($mall_ids as $mid){
                        $insert = array(
                            'news_id' => $id,
                            'mall_id' => $mid,
                            'created_at' => date('Y-m-d H:i:s'),
                        );
                        $this->news_mall_model->insert($insert);
                    }
                }

                if ($this->db->trans_status() === FALSE)
                {
                    $this->db->trans_rollback();
                    response_json([],'101',"更新失败，请重试!");
                }
                else
                {
                    $this->db->trans_commit();
                    response_json();
                }
            }
        }

        if($opt == 'del')
        {
            $id   = (integer)$this->input->get_post('id');
            $info = $this->news_model->get_by_id($id);
            if(empty($info))
            {
                response_json([],'101',"参数错误!");
            }
            // 事务开始
            $this->db->trans_strict(FALSE); // 关闭严格模式，以免死锁
            $this->db->trans_begin();

            // 移除店铺关系
            $this->news_mall_model->delete_where('news_id',$id);
            // 移除店铺标签
            $this->news_data_tag_model->delete_where('news_id',$id);

            $this->news_model->delete($id);

            $where = array(
                $this->news_id => $id,
            );
            $this->db->delete('news_bodies', $where);


            if ($this->db->trans_status() === FALSE)
            {
                $this->db->trans_rollback();
                response_json([],'101',"删除失败，请重试!");
            }
            else
            {
                $this->db->trans_commit();
                response_json();
            }
            response_json();
        }

        $limit     = intval($this->input->get('limit')) > 0 ? $this->input->get('limit') : 20;
        $cur_page      = intval($this->input->get('page'));
        $cur_page   = $cur_page > 0 ? $cur_page : 1;
        $offset     = ($cur_page - 1) * $limit;

        $q			= (string)$this->input->get('q');

        $where      = "";

        if(!empty($q))
        {
            $where  .= "where (`today` like '%".$q."%')";
        }

        $order_by   = "order by `id` desc";
        $result     = $this->report_model->result_data($where, $order_by, $offset, $limit);
        $total      = $this->report_model->result_count($where);

        if($total > 0){
            $_data['code'] = 0;
            $_data['msg'] = 'ok';
        }else{
            $_data['code'] = 101;
            $_data['msg'] = '无数据';
        }
        $_data['data'] = $result;
        $_data['count'] = $total;

        echo json_encode($_data);
    }

    public function cates(){
        // 查询所有版块
        $forums = $this->news_types_model->result_all();
        $res = array();
        $this->math_forum($forums,0,0,[],$res);
        response_json($res);
    }
    
    public function info(){
        $id   = (integer)$this->input->get_post('id');
        $info = $this->news_model->get_by_id($id);
        if(empty($info))
        {
            response_json([],'101',"参数错误!");
        }
        // 查询当前主题的标签，并处理
        $where = "where news_id=".$id;
        $tags = $this->news_data_tag_model->result_data($where);
        $tag = "";
        if(!empty($tags)){
            $tag = implode(",",array_column($tags,'tag_name'));
        }
        // 查询关联店铺
        $where = "where news_id=".$id;
        $malls = $this->news_mall_model->result_data($where);
        $mall_ids = "";
        if(!empty($malls)){
            $mall_ids = implode(",",array_column($malls,'mall_id'));
        }
        // 查询内容
        $body = $this->news_bodies_model->get_by_field('news_id',$id);
        if(!empty($body)){
            $body = $body['body'];
        }
        $data   = array(
            'info' => $info,
            'body' => $body,
            'tags' => $tag,
            'mall_ids' => $mall_ids
        );
        response_json($data);
    }

    /**
     * 归类列取版块分类
     * @param $curr_category
     * @param $id
     * @param $level
     * @param array $list
     * @param $res
     * @return array
     */
    private function math_forum($curr_category,$id,$level,$list=[],&$res){
        $list =array();
        foreach ($curr_category as $k=>$v){
            if ($v['parent_id'] == $id){
                for($i=0;$i<$level;$i++){
                    $v['name'] = "--".$v['name'];
                }
                $res[] = $v;
                $math_res = $this->math_forum($curr_category,$v['id'],$level+1,[],$res);
                $v['son'] = $math_res;
                $list[] = $v;
            }
        }
        return $list;
    }
}